﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using BUS;
using Entity;
using Share;

namespace SLMNG
{
    public partial class M_frmPurchase : BaseForm
    {
        dsCatalogue.ImportDetailsDataTable dt;
        DataTable dtItem;

        #region Constructor and form event

        public M_frmPurchase()
        {
            InitializeComponent();
            this.Load += new EventHandler(Form1_Load);
            //FortmatGrid();
            //dt = new dsCatalogue.ImportDetailsDataTable();
          
            dtItem = new DataTable();
        }

        private void FortmatGrid()
        {
            DataTable dtTemp = new DataTable();
            DataColumn dc1 = new DataColumn("MaterialCode");
            DataColumn dc2 = new DataColumn("MaterialName");
            DataColumn dc3 = new DataColumn("UnitCost");
            DataColumn dc4 = new DataColumn("Weight");
            DataColumn dc5 = new DataColumn("Amount");
            dtTemp.Columns.AddRange(new[] { dc1, dc2, dc3, dc4, dc5 });
            grvMaterial.DataSource = dtTemp;
            //grvMaterial.DataSource = dt;
            gridViewMaterial.Columns["UnitCost"].DisplayFormat.FormatString = Global.CurrencyFormat;
            gridViewMaterial.Columns["UnitCost"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
            gridViewMaterial.Columns["Amount"].DisplayFormat.FormatString = Global.CurrencyFormat;
            gridViewMaterial.Columns["Amount"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
            gridViewMaterial.Columns["Weight"].DisplayFormat.FormatString = Global.FORMAT_NUMBER;
            gridViewMaterial.Columns["Weight"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
            gridViewMaterial.CellValueChanged += gridView1_CellValueChanged;

            //repositoryItemLookUpEdit1.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("ItemName"));
            //repositoryItemLookUpEdit1.DisplayMember = "ItemName";
            //repositoryItemLookUpEdit1.ValueMember = "ItemCode";
        }

        void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.Name.Equals("UnitCost") || e.Column.Name.Equals("Weight"))
            {
                decimal unitCost = Global.decimalParse( gridViewMaterial.GetRowCellValue(e.RowHandle, "UnitCost"));
                decimal weight = Global.decimalParse(gridViewMaterial.GetRowCellValue(e.RowHandle, "Weight"));
                gridViewMaterial.SetRowCellValue(e.RowHandle, "Amount", unitCost * weight);
            }
        }

        void Form1_Load(object sender, EventArgs e)
        {

            //DataTable dtTemp = new DataTable();
            //DataColumn dc1 = new DataColumn("MaterialCode");
            //DataColumn dc2 = new DataColumn("MaterialName");
            //DataColumn dc3 = new DataColumn("UnitCost");
            //DataColumn dc4 = new DataColumn("Weight");
            //DataColumn dc5 = new DataColumn("Amount");
            //dtTemp.Columns.AddRange(new[] { dc1, dc2, dc3, dc4, dc5 });
            //grvMaterial.DataSource = dtTemp;
            FortmatGrid();
            
            txtCode.Text = AutoConfigCode.GetNextNumber(AutoNumberCode.IPO.ToString());
            dtpDate.EditValue = DateTime.Now;

            string[] arg = new string[] { "MaterialCode" };
            object[] obj = new object[] { DBNull.Value };
            repositoryItemLookUpEdit1.DataSource = CatalogueBase.GetData(Material.STORE_SELECT, arg, obj).Tables[0];

            //arg = new string[] { "ServiceID" };
            //obj = new object[] { DBNull.Value };
            //DataSet ds1 = CatalogueBase.GetData("usp_Services_Select", arg, obj);
            //gridView.DataSource = ds1.Tables[0];
        }

        #endregion

        #region Overrides Methods

        public void Save()
        {
            

            
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (txtCode.Text.Trim().Equals(string.Empty))
            {
                Global.ShowMessageBox("Chưa có mã phiếu nhập !", this.Text);
                return;
            }
            string codeList = string.Empty;
            for (int i = 0; i < gridViewMaterial.RowCount; i++)
            {
                codeList += gridViewMaterial.GetRowCellValue(i, "MaterialCode").ToString() + ",";
            }

            if (codeList.EndsWith(","))
                codeList = codeList.Remove(codeList.Length - 1, 1);

            DlgSelectMaterials dlg = new DlgSelectMaterials(codeList);
            dlg.ShowDialog();
            if (dlg.DialogResult == System.Windows.Forms.DialogResult.OK)
            {
                DataTable dt1 = dlg.dtResult;

                dt1.Columns.Add("ImportCode", typeof(string));
                foreach (DataRow dr in dt1.Rows)
                {
                    dr["ImportCode"] = txtCode.Text;
                }
                foreach (DataRow item in dt1.Rows)
                {
                    dt.ImportRow(item);
                }
            }            
        }


        public override void fncInsert()
        {
            
        }

        public override void fncSave()
        {
            if (string.IsNullOrEmpty(txtCode.Text.Trim()))
            {
                MessageBox.Show(temp.ID_IS_NOT_NULL);
                return;
            }
            else if (gridViewMaterial.RowCount <= 0)
            {
                MessageBox.Show("Lưới phải có ít nhất 1 dòng!");
                return;
            }

            DataSet ds = new DataSet();

            decimal totalAmount = 0;

            DataTable dt2 = dt.Copy();
            dt2.TableName = "ImportDetails";
            dt2.Columns.Remove("MaterialName");
            for (int i = 0; i < dt2.Rows.Count; i++)
            {
                decimal amount = Global.decimalParse(dt2.Rows[i]["Amount"]);
                if (amount <= 0)
                {
                    dt2.Rows.RemoveAt(i);
                    i--;
                }
                else
                    totalAmount += amount;
            }

            DataTable dt1 = new DataTable();
            dt1.Columns.Add("ImportCode", typeof(string));
            dt1.Columns.Add("ImportDate", typeof(DateTime));
            dt1.Columns.Add("TotalAmount", typeof(decimal));
            dt1.Columns.Add("CreatedBy", typeof(string));
            dt1.Columns.Add("Description", typeof(string));

            DataRow dr = dt1.NewRow();
            dr["ImportCode"] = txtCode.Text.Trim();
            dr["ImportDate"] = dtpDate.EditValue;
            dr["Description"] = txtDescription.Text.Trim();
            dr["TotalAmount"] = totalAmount;
            dr["CreatedBy"] = Global.UserID;
            dt1.Rows.Add(dr);

            ds.Tables.Add(dt1);            
            ds.Tables.Add(dt2);

            string[] arg = new string[] { Import.STORE_INSERT, ImportDetail.STORE_INSERT };
            string result = CatalogueBase.SaveData(arg, ds);
            if (result == "0")
            {
                ClearForm();
                MessageBox.Show(temp.STATUS_INSERT_SUCCESS, this.Text);
            }
            else
                MessageBox.Show(HandleException.HandleSQLException(result), this.Text);
        }

        private void ClearForm()
        {
            txtCode.Text = string.Empty;
            txtDescription.Text = string.Empty;
            dt.Clear();
        }

        public override void fncEdit()
        {
            
        }

        public override void fncDelete()
        {
            
        }

        public override void fncRefresh()
        {
            
        }

        public override void fncPrint()
        {
            
        }

        #endregion

        #region Support Methods

        

        #endregion

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (gridViewMaterial.RowCount > 9)
            {
                int num = gridViewMaterial.SelectedRowsCount;
                if (MessageBox.Show("Bạn muốn xóa " + num.ToString() + " dòng đã chọn?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    for (int i = 0; i < gridViewMaterial.SelectedRowsCount; i++)
                    {
                        if (gridViewMaterial.GetSelectedRows()[i] >= 0)
                        {
                            string code = gridViewMaterial.GetRowCellValue(gridViewMaterial.GetSelectedRows()[i], "MaterialCode").ToString();
                            for (int j = dt.Rows.Count - 1; j >= 0; j--)
                            {
                                if (dt.Rows[j]["MaterialCode"].ToString() == code)
                                {
                                    dt.Rows.RemoveAt(j);
                                    i--;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
